package com.lbj.mvvm.base

import android.app.Application
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy

open class JetpackApp : Application(), ViewModelStoreOwner {

    lateinit var mAppVMStore: ViewModelStore

    private var mFactory: ViewModelProvider.Factory? = null

    override fun getViewModelStore(): ViewModelStore = mAppVMStore

    override fun onCreate() {
        super.onCreate()

        val formatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(false)      //（可选）是否显示线程信息。 默认值为true
            .methodCount(2)               // （可选）要显示的方法行数。 默认2
            .methodOffset(7)               // （可选）设置调用堆栈的函数偏移值，0的话则从打印该Log的函数开始输出堆栈信息，默认是0
            .tag("TAG")                  //（可选）每个日志的全局标记。 默认PRETTY_LOGGER（如上图）
            .build()
        Logger
            .addLogAdapter(AndroidLogAdapter(formatStrategy))
        mAppVMStore = ViewModelStore()
    }

    /**
     * 获取一个全局的ViewModel
     */
    fun getAppVMProvider(): ViewModelProvider = ViewModelProvider(this, this.getAppFactory())

    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }
}